﻿using System;
using System.Linq;

namespace FranceTriple.Dal
{
    public class ApplicationSettingDal
    {
        private String MaximumOnlineUsersAndDateLocalized = "MaximumOnlineUsersAndDate".ToLocalizedString();
        private static Int32 compared;

        public static Int32 MaximumOnlineUsers
        {
            get
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    return Int32.Parse((from app in ctx.ApplicationSettingSet
                                        where app.Name == "MaximumOnlineUsers"
                                        select app.Value).FirstOrDefault());
                }
            }
            set
            {
                compared = Math.Max(MaximumOnlineUsers, value);
                //Todo : Mettre en cache MaximumOnlineUsers coté Web
                // Le test ci-dessous resterait juste par sécurité.
                if (compared == value)
                {
                    using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                    {
                        if (MaximumOnlineUsers != value)
                            (from app in ctx.ApplicationSettingSet
                             where app.Name == "MaximumOnlineUsers"
                             select app).FirstOrDefault().Value = compared.ToString();

                        //Mettre à jour la date en cas d'égalité du nombre d'utilisateurs.
                        MaximumOnlineDate = DateTime.UtcNow.ToString();

                        ctx.SaveChanges();
                    }
                }
            }
        }

        public static String MaximumOnlineDate
        {
            get
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    return (from app in ctx.ApplicationSettingSet where app.Name == "MaximumOnlineDate" select app.Value).FirstOrDefault();
                }
            }
            set
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    (from app in ctx.ApplicationSettingSet
                     where app.Name == "MaximumOnlineDate"
                     select app).FirstOrDefault().Value = String.Format("{0:G}", value);
                    ctx.SaveChanges();
                }
            }
        }

        public string MaximumOnlineUsersAndDate
        {
            get
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    return String.Format(MaximumOnlineUsersAndDateLocalized, MaximumOnlineUsers, MaximumOnlineDate);
                }
            }
        }
    }
}
